package com.bosssoft.trainee.gateway.component;

import com.bosssoft.trainee.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.ReactiveAuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

/**
 * @Author: wuxin
 * @Project: rbac-SpringCloud
 * @Date: 2022/7/15
 * @Description:
 */
@Slf4j
@Component
public class MyAuthenticationManager implements ReactiveAuthenticationManager {
    @Autowired
    ReactiveUserDetailsService reactiveUserDetailsService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Override
    public Mono<Authentication> authenticate(Authentication authentication) {
        String tokenString = (String) authentication.getPrincipal();

        // 读取token
        String username = getUsername(tokenString);
        log.info("MyAuthenticationManager username = {}", username);
        if (!StringUtils.hasLength(username)){
            return Mono.just(new UsernamePasswordAuthenticationToken(null,null));
        }
        Mono<UserDetails> mono = reactiveUserDetailsService.findByUsername(username);
        UserDetails userDetails=null;
        if (mono!=null){
            userDetails= reactiveUserDetailsService.findByUsername(username).block();
        }
        if (userDetails!=null){
            return Mono.just(new UsernamePasswordAuthenticationToken(userDetails.getUsername(),null));
        }
        return Mono.just(new UsernamePasswordAuthenticationToken(null,null));

    }

    /**
     * 读取Jwt Token转化成为Username
     *
     * @param authorization
     * @return
     */
    private String getUsername(String authorization) {

        if (!StringUtils.hasText(authorization)) {
            return null;
        }

        boolean valid = authorization.startsWith(tokenHead);
        if (!valid) {
            return null;
        }

        return jwtTokenUtil.getUserNameFromToken(authorization.replace(tokenHead, ""));
    }
}
